package com.ujiuye.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class BaseDao<T> {
    static ComboPooledDataSource ds = null;
    static QueryRunner qr = null;
    static{
        ds = new ComboPooledDataSource();//创建c3p0的连接池对象
        qr = new QueryRunner(ds);
    }
    //封装增删改方法
    public int update(String sql,Object...params){
        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    //单行查询
    public T queryOne(String sql,Class<T> clazz,Object...params){
        try {
            return qr.query(sql,new BeanHandler<>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    //多行查询
    public List<T> queryMore(String sql, Class<T> clazz, Object...params){
        try {
            return qr.query(sql,new BeanListHandler<>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    //聚合查询
    public Number queryScar(String sql,Object...params){
        try {
            return qr.query(sql,new ScalarHandler<Number>(),params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
